//
//  LLSearchViewController.m
//  LLSearchView
//
//  Created by 王龙龙 on 2017/7/25.
//  Copyright © 2017年 王龙龙. All rights reserved.
//搜索VC

#import "LLSearchViewController.h"
#import "LLSearchView.h"//搜索的view
#import "LLSearchResultViewController.h"//搜索结果VC
#import "LLSearchSuggestionVC.h"//搜索提示VC----暂未使用

@interface LLSearchViewController ()<UISearchBarDelegate,LLSearchViewDelegate,UIGestureRecognizerDelegate>
/**搜索框*/
@property (nonatomic, strong) UISearchBar *searchBar;
/**搜索的view*/
@property (nonatomic, strong) LLSearchView *searchView;
/**热门搜索的数组*/
@property (nonatomic, strong) NSMutableArray *hotArray;
/**历史搜索的数组*/
@property (nonatomic, strong) NSMutableArray *historyArray;
/**搜索提示VC*/
@property (nonatomic, strong) LLSearchSuggestionVC *searchSuggestVC;

@end
@implementation LLSearchViewController
#pragma mark- init初始化
- (void)viewDidLoad{
    [super viewDidLoad];
    [self requestHotSearchData];
    [self setBarButtonItem];
    [self pd_addReturnKeyBoard];
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.searchSuggestVC.view];
    [self addChildViewController:self.searchSuggestVC];
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    if (!_searchBar.isFirstResponder) {
        [self.searchBar becomeFirstResponder];
    }
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    // 回收键盘
    [self.searchBar resignFirstResponder];
    self.searchSuggestVC.view.hidden = YES;
    self.navigationController.navigationBarHidden=NO;
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if (!self.tabBarController.tabBar.isHidden) {
        self.tabBarController.tabBar.hidden = YES;
    }
}
- (LLSearchView *)searchView{
    if (!_searchView) {
        _searchView = [[LLSearchView alloc] initWithFrame:CGRectMake(0, BY_Nav_H, KSCREEWIDTH, KSCREEHEGIHT - BY_Nav_H) hotArray:self.hotArray historyArray:self.historyArray];
        __weak LLSearchViewController *weakSelf = self;
        _searchView.delegate = self;
        _searchView.tapAction = ^(NSString *str) {//点击了搜索View上的搜索条件
            [weakSelf pushToSearchResultWithSearchStr:str];
        };
    }
    return _searchView;
}
- (void)setBarButtonItem{
    [self.navigationItem setHidesBackButton:YES];
    // 创建搜索框
    UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(5, 7, self.view.frame.size.width, 30)];
    UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 5, CGRectGetWidth(titleView.frame) - 15, 20)];
    searchBar.placeholder = @"搜索内容";
    searchBar.delegate = self;
    searchBar.showsCancelButton = YES;
    searchBar.barStyle = UISearchBarStyleMinimal;
    UIView *searchTextField = searchTextField = [searchBar valueForKey:@"_searchField"];
    searchTextField.backgroundColor = [UIColor colorWithRed:234/255.0 green:235/255.0 blue:237/255.0 alpha:1];
    [searchTextField setBackgroundColor:[UIColor whiteColor]];
    searchTextField.layer.cornerRadius = 14.0f;
    searchTextField.layer.borderColor = RGBA(152, 152, 152, 1).CGColor;
    searchTextField.layer.borderWidth = 1;
    searchTextField.layer.masksToBounds = YES;
    [searchBar setImage:[UIImage imageNamed:@"sort_magnifier"] forSearchBarIcon:UISearchBarIconSearch state:UIControlStateNormal];
    UIButton *cancleBtn = [searchBar valueForKey:@"cancelButton"];
    //修改标题和标题颜色
    [cancleBtn setTitle:@"取消" forState:UIControlStateNormal];
    [cancleBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    
    [titleView addSubview:searchBar];
    self.searchBar = searchBar;
    [self.searchBar becomeFirstResponder];
    self.navigationItem.titleView = searchBar;
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:self action:nil];
}
- (LLSearchSuggestionVC *)searchSuggestVC{//搜索提示VC
    if (!_searchSuggestVC) {
        self.searchSuggestVC = [[LLSearchSuggestionVC alloc] init];
        _searchSuggestVC.view.frame = CGRectMake(0, BY_Nav_H, KSCREEWIDTH, KSCREEHEGIHT - BY_Nav_H);
        _searchSuggestVC.view.hidden = YES;
        __weak LLSearchViewController *weakSelf = self;
        _searchSuggestVC.searchBlock = ^(NSString *searchTest) {
            [weakSelf pushToSearchResultWithSearchStr:searchTest];
        };
    }
    return _searchSuggestVC;
}

#pragma mark - UISearchBarDelegate
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{//点击了键盘上的搜索按钮
    [self.searchBar resignFirstResponder];
    [self pushToSearchResultWithSearchStr:searchBar.text];
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
    [self.searchBar resignFirstResponder];
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar{
    searchBar.showsCancelButton = YES;
}

#pragma mark- 数据处理
- (NSMutableArray *)hotArray{//热门搜索的数组
    if (!_hotArray) {
        self.hotArray = [[NSMutableArray  alloc]init];
    }
    return _hotArray;
}
- (NSMutableArray *)historyArray{//历史搜索的数组
    if (!_historyArray) {
        _historyArray = [NSKeyedUnarchiver unarchiveObjectWithFile:KHistorySearchPath];
        if (!_historyArray) {
            self.historyArray = [NSMutableArray array];
        }
    }
    return _historyArray;
}

#pragma mark- 用户交互
- (void)pd_addReturnKeyBoard {//给当前view添加手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(viewKeyBoardHiddenClick)];
    tap.numberOfTapsRequired = 1;
    tap.numberOfTouchesRequired = 1;
    tap.delegate = self;
    [self.view addGestureRecognizer:tap];
}
-(void)viewKeyBoardHiddenClick{
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [appDelegate.window endEditing:YES];
}
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    if ([NSStringFromClass([touch.view class]) isEqualToString:@"UITableViewCellContentView"]) {//判断如果点击的是tableView的cell，就把手势给关闭了
        return NO;//关闭手势
    }//否则手势存在
    return YES;
}
- (void)pushToSearchResultWithSearchStr:(NSString *)str{//跳转至搜索结果页
    self.searchBar.text = str;
    LLSearchResultViewController *searchResultVC = [[LLSearchResultViewController alloc] init];
    searchResultVC.searchStr = str;
    searchResultVC.hotArray = _hotArray;
    searchResultVC.historyArray = _historyArray;
    [self.navigationController pushViewController:searchResultVC animated:YES];
    [self setHistoryArrWithStr:str];
}
- (void)setHistoryArrWithStr:(NSString *)str{//记录最近搜索的值
    for (int i = 0; i < _historyArray.count; i++) {
        if ([_historyArray[i] isEqualToString:str]) {
            [_historyArray removeObjectAtIndex:i];
            break;
        }
    }
    [_historyArray insertObject:str atIndex:0];
    [NSKeyedArchiver archiveRootObject:_historyArray toFile:KHistorySearchPath];
}
-(void)typeClick:(NSString *)str{//点击了推荐结果的cell
    for (BYSetModel *models in APPDELEGATE.SetDataArray) {
        if ([models.setting_name isEqualToString:@"guide-travel-detail"]) {
            NSString *urlStr = models.setting_value;
            NSString *paramStr = [NSString stringWithFormat:@"id=%@&userid=%@&token=%@",str,[SaveCacheData loadDataStrWithKey:currentUserudid] ==nil?@"":[SaveCacheData loadDataStrWithKey:currentUserudid],[SaveCacheData loadDataStrWithKey:currentUserToken] ==nil?@"":[SaveCacheData loadDataStrWithKey:currentUserToken]];
            
            NSString *webURL= @"";
            if ([urlStr rangeOfString:@"?"].location == NSNotFound) {//没有?参数
                webURL = [NSString stringWithFormat:@"%@?%@",urlStr,paramStr];
            } else {//有参数
                webURL = [NSString stringWithFormat:@"%@&%@",urlStr,paramStr];
            }
            BYWebVC *VC = [[BYWebVC alloc]init];
            VC.url = webURL;
            [self.navigationController pushViewController:VC animated:YES];
        }
    }
}

#pragma mark- 网络请求
-(void)requestHotSearchData{//请求热门搜索的数据
    NSDictionary *dict;
    [BYNetworking requestGetOrPostWithType:GET url:LJURL_psearch_popular params:dict success:^(NSInteger code, NSString * _Nonnull msg, id  _Nonnull data) {
        NSMutableArray *array = [data objectForKey:@"data"];
        for (NSDictionary *dic in array) {
            [self.hotArray addObject: dic[@"keyword"]];
        }
        [self.view addSubview:self.searchView];
    } fail:^(NSError * _Nonnull error) {
    } showHUD:YES];
}


@end
